package com.yutel.socket;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import cn.com.xinli.mobile.packet.AbstractPacket;

public class ServerObject {
	private static ServerObject ss;
	private ServerSocket server;
	private int port;

	private ServerObject() {
	}

	public static ServerObject getInstance() {
		if (ss == null) {
			ss = new ServerObject();
		}
		return ss;
	}

	public void start() {
		Socket socket = null;
		ObjectInputStream in = null;
		ObjectOutputStream out = null;
		try {
			server = new ServerSocket(getPort());
			while (true) {
				socket = server.accept();
				in = new ObjectInputStream(socket.getInputStream());
				AbstractPacket packet = (AbstractPacket) in.readObject();
				System.out.println(packet.toString());
				out = new ObjectOutputStream(socket.getOutputStream());
				out.writeObject("OK");
				socket.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void stop() {
		try {
			ss.stop();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public static void main(String[] args) {
		ServerObject s = ServerObject.getInstance();
		s.setPort(9080);
		s.start();
	}

}
